<!DOCTYPE html>



  


<html class="theme-next muse use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Hexo, NexT" />










<meta name="description" content="该系列已分别介绍了服务端、客户端的启动流程、网络读事件处理流程，本文将重点剖析Netty是如何封装NIO的写事件。  温馨提示：本文虽然是源码分析，但强烈建议精读，因为根据源码阐述其背后的设计哲学，也用黑体进行了标注，请特别留意。  在阅读本篇文章之前，请稍微思考如下几个问题：  写事件需要先注册才能往通道中写入数据？ 什么时候需要向通道注册写事件呢？ 业务线程池执行业务逻辑后，是如何通过IO线程">
<meta property="og:type" content="article">
<meta property="og:title" content="大厂Offer收割机：Netty优雅的网络写设计之连坏4问">
<meta property="og:url" content="https://www.codingw.net/posts/434e75fd.html">
<meta property="og:site_name" content="中间件兴趣圈">
<meta property="og:description" content="该系列已分别介绍了服务端、客户端的启动流程、网络读事件处理流程，本文将重点剖析Netty是如何封装NIO的写事件。  温馨提示：本文虽然是源码分析，但强烈建议精读，因为根据源码阐述其背后的设计哲学，也用黑体进行了标注，请特别留意。  在阅读本篇文章之前，请稍微思考如下几个问题：  写事件需要先注册才能往通道中写入数据？ 什么时候需要向通道注册写事件呢？ 业务线程池执行业务逻辑后，是如何通过IO线程">
<meta property="og:locale">
<meta property="og:image" content="https://img-blog.csdnimg.cn/202103292342433.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20210329235337678.png#pic_center">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20210330211203768.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center">
<meta property="og:image" content="https://img-blog.csdnimg.cn/2021033021290030.png#pic_center">
<meta property="og:image" content="https://img-blog.csdnimg.cn/202103302132261.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center">
<meta property="og:image" content="https://img-blog.csdnimg.cn/2021033021413799.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20210331231749520.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20210331232959731.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20210331233940633.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20210331234441987.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20210331235204870.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20210401000506855.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center">
<meta property="og:image" content="https://img-blog.csdnimg.cn/2021032212002741.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20190314214003962.jpg?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center">
<meta property="article:published_time" content="2021-03-31T16:17:01.000Z">
<meta property="article:modified_time" content="2021-04-26T15:34:07.593Z">
<meta property="article:author" content="中间件兴趣圈">
<meta property="article:tag" content="中间件">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://img-blog.csdnimg.cn/202103292342433.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '',
    scheme: 'Muse',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://www.codingw.net/posts/434e75fd.html"/>





  <title>大厂Offer收割机：Netty优雅的网络写设计之连坏4问 | 中间件兴趣圈</title>
  








<meta name="generator" content="Hexo 5.4.0"></head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">中间件兴趣圈</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">微信搜『中间件兴趣圈』，回复『Java』获取200本优质电子书</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            归档
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://www.codingw.net/posts/434e75fd.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="中间件兴趣圈">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">大厂Offer收割机：Netty优雅的网络写设计之连坏4问</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2021-04-01T00:17:01+08:00">
                2021-04-01
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/netty/" itemprop="url" rel="index">
                    <span itemprop="name">netty</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          
             <span id="/posts/434e75fd.html" class="leancloud_visitors" data-flag-title="大厂Offer收割机：Netty优雅的网络写设计之连坏4问">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv"><i class="fa fa-file-o"></i>
            <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>次
            </span>
          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <div id="vip-container"><p>该系列已分别介绍了服务端、客户端的启动流程、网络读事件处理流程，本文将重点剖析Netty是如何封装NIO的写事件。</p>
<blockquote>
<p>温馨提示：本文虽然是源码分析，但强烈建议精读，因为根据源码阐述其背后的设计哲学，也用黑体进行了标注，请特别留意。</p>
</blockquote>
<p>在阅读本篇文章之前，请稍微思考如下几个问题：</p>
<ul>
<li>写事件需要先注册才能往通道中写入数据？</li>
<li>什么时候需要向通道注册写事件呢？</li>
<li>业务线程池执行业务逻辑后，是如何通过IO线程将数据写入到网络中的呢？</li>
<li>Netty中如何针对写限流</li>
</ul>
<h2 id="1、写事件概述"><a href="#1、写事件概述" class="headerlink" title="1、写事件概述"></a>1、写事件概述</h2><p>写事件，顾名思义，就是将数据写入网络，通过网络传输给接收端，通常我们知道业务都会在专属的业务线程池中执行，那数据是如何通过IO线程写入网络中的呢？<br><img src="https://img-blog.csdnimg.cn/202103292342433.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70" alt="在这里插入图片描述"><br>正如上图中的线程模型，业务线程池是如何将数据通过IO线程写入网络中的呢？</p>
<p>接下来我们将带着问题，尝试看Netty是如何封装NIO的写事件。</p>
<h2 id="2、写事件处理流程分析"><a href="#2、写事件处理流程分析" class="headerlink" title="2、写事件处理流程分析"></a>2、写事件处理流程分析</h2><p>在Netty中，写事件的处理入口为NioEventLoop的processSelectedKey方法：<br><img src="https://img-blog.csdnimg.cn/20210329235337678.png#pic_center" alt="在这里插入图片描述"><br>根据调用链，最终调用AbstractChannel的内部类AbstractUnsafe的flush0方法。<br><img src="https://img-blog.csdnimg.cn/20210330211203768.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center" alt="AbstractUnsafe#flush0"><br>该方法有三个实现要点：</p>
<ul>
<li>获取写缓存队列，如果写缓存队列为空，则跳过本次写事件。每一个通道独享一个写缓存队列，写事件触发执行的动作就是要将写缓存中的数据写入到网络中。</li>
<li>如果通道处于未激活状态，需要清理写缓存区</li>
<li>通过调用doWrite方法将写缓存中的数据写入网络通道中。</li>
</ul>
<p>接下来将详细介绍上述关键步骤。</p>
<h4 id="2-1-NIO写事件的优雅封装"><a href="#2-1-NIO写事件的优雅封装" class="headerlink" title="2.1 NIO写事件的优雅封装"></a>2.1 NIO写事件的优雅封装</h4><p>首先，我们将写缓存区当成一个黑盒，先重点看一下doWrite方法的实现，窥探一下Netty是如何基于NIO来处理网络写入的。<br><img src="https://img-blog.csdnimg.cn/2021033021290030.png#pic_center" alt="在这里插入图片描述"><br>Step1：如果写缓存区中没有可写的数据，<strong>取消注册写事件</strong>。我们来看一下取消写事件的经典实现技巧：<br><img src="https://img-blog.csdnimg.cn/202103302132261.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center" alt="在这里插入图片描述"><br>首先判断一下注册键是否有效，然后通过为位运算，取消写事件。</p>
<p><strong>思考题：问题来了，取消写事件，从系统层面就无法继续触发写操作了，那后续如何触发写事件呢？</strong></p>
<p><img src="https://img-blog.csdnimg.cn/2021033021413799.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center" alt="在这里插入图片描述"><br>写事件的处理要考虑如下几个问题：</p>
<ul>
<li>本次写缓存区中数据是否写完？</li>
<li>如果底层网络Socket缓存区积压，导致写缓冲区未写完如何处理？</li>
<li>如果网络缓存区数据特别大又如何处理？</li>
</ul>
<p>Netty给出的解决方案如下：</p>
<ul>
<li>通过底层NIO的SocketChannel的write方法将数据写入到Socket缓存区，<strong>如果返回值为０，表示Socket缓冲区已满，需要暂停写入，具体做法，注册写事件，等待下次继续写入。</strong></li>
<li>如果写缓存区的数据全部处理完毕，<strong>可取消注册写事件</strong>，避免毫无意义的写事件就绪。</li>
<li>如果写缓存区中数据很大，为了避免单个通道对其他通道的影响，默认设置单次写事件最多调用底层NIO SocketChannel的write方法次数，默认为16。</li>
</ul>
<p>写事件的核心处理要点就介绍到这里了。</p>
<h4 id="2-2-通道写缓冲区详解"><a href="#2-2-通道写缓冲区详解" class="headerlink" title="2.2 通道写缓冲区详解"></a>2.2 通道写缓冲区详解</h4><p>在Netty中调用通道的write方法并不会立即将数据写入到底层网络Socket中，而是写入到“写缓存区”，为应用级别的缓存区，即<strong>ChannelOutboundBuffer</strong>，这是Netty实现<strong>写操作最重要的一个数据结构</strong>。</p>
<h5 id="2-2-1-类图"><a href="#2-2-1-类图" class="headerlink" title="2.2.1 类图"></a>2.2.1 类图</h5><p>ChannelOutboundBuffer 的核心类图如下：<br><img src="https://img-blog.csdnimg.cn/20210331231749520.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70" alt="在这里插入图片描述"><br>核心属性与方法简介：</p>
<ul>
<li>FastThreadLocal&lt;ByteBuffer[]&gt; NIO_BUFFERS<br>可以看出是线程本地变量ThreadLocal的优化版本，存储一个一个ByteBuffer数组。</li>
<li>Channel channel<br>该写缓存区所属的通道，每一个Channel独享一个写缓冲区。</li>
<li>Entry flushedEntry<br>表示第一个被刷新的Entry,在写入时，从该Entry开始写。</li>
<li>Entry unflushedEntry<br>在链表中第一个未刷新的节点(未刷新链表中第一个节点)。</li>
<li>Entry tailEntry<br>在链表中尾部的节点。</li>
<li>int flushed<br>待写入的entry个数，这个数据代表在执行一次真正的flush(flush0),将会有多少个entry中的内容会被写入到通道。</li>
</ul>
<p>接下来我们按照写事件对待写入缓存区方法调用的顺序来讲解一下该方法的核心实现逻辑。</p>
<h5 id="2-2-2-size方法详解"><a href="#2-2-2-size方法详解" class="headerlink" title="2.2.2  size方法详解"></a>2.2.2  size方法详解</h5><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">size</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> flushed;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>返回本次写缓存区可期望刷新的消息个数(Entry)。在NioSocketChannel的doWriter方法中，如果isEmpty返回true,直接结束本次写入操作，更加准确的是结束本次flush操作。</p>
<p>flushed该字段代表的当时待写入的Entry,如果为0，<strong>表示没有待flush的Entry,但不代表ChannelOutboundBuffer中没有Entry存在</strong>，比如调用Channel.writer方法，会往ChannelOutboundBuffer增加Entry,但在没有调用addFlush方法之前，ChannelOutboundBuffer中的flushed 字段的值不会增加。</p>
<h5 id="2-2-3-addMessage方法详解"><a href="#2-2-3-addMessage方法详解" class="headerlink" title="2.2.3  addMessage方法详解"></a>2.2.3  addMessage方法详解</h5><p><img src="https://img-blog.csdnimg.cn/20210331232959731.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center" alt="在这里插入图片描述"><br>向写缓存中添加消息，方法本身的实现非常简单，因为ChannelOutboundBuffer其内部数据结构为一个链表，这是一个往链表中添加消息的过程，这里的<strong>关键点</strong>是该方法的调用入口为Channel的write方法，即调用<strong>通道的write方法只是将数据写入到写缓存，并不会触发真正的往网络中写消息。</strong></p>
<p>该方法会调用incrementPendingOutboundBytes，我们简单看一下该方法的实现细节：<br><img src="https://img-blog.csdnimg.cn/20210331233940633.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center" alt="在这里插入图片描述"><br>该方法蕴含了Netty一个<strong>非常重要的机制，写操作限流，高低水位线机制。</strong><br>当缓存区中存储的数据超过了设置的高水位线(阔值)，则会设置为不可写，并向通道<strong>传播写状态变更事件</strong>。</p>
<h5 id="2-2-4-addMessage方法详解"><a href="#2-2-4-addMessage方法详解" class="headerlink" title="2.2.4  addMessage方法详解"></a>2.2.4  addMessage方法详解</h5><p><img src="https://img-blog.csdnimg.cn/20210331234441987.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70" alt="在这里插入图片描述"><br><strong>该方法并没有真正的执行刷新动作，而是计算可刷写的Entry个数</strong>，一次刷新动作，会将unfluedEntry开始，一直扫描到tailEntry。</p>
<p><strong>同样这里和Netty的写限流有关，将数据刷写后，会减少缓存区中的大小，如果低于设置的低水位线，会将缓存区恢复到可写状态。</strong></p>
<p>该方法的调用入口为下图：<br><img src="https://img-blog.csdnimg.cn/20210331235204870.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center" alt="在这里插入图片描述"><br><strong>即在调用通道的flush方法时会先计算本次看刷写到Socket缓存区中的数据，然后执行flush0方法执行真正的网络写</strong>，该方法在第一部分中已详细介绍。</p>
<p>本文就介绍到这里了，文章开头的问题大家是否有了自己的理解了呢？欢迎私信或留言与我交流互动，让我们在交流中共同进步。</p>
<p><strong>一键三连是对我最大的支持与肯定</strong></p>
<p><strong>为了让大家在实战中学习Netty，笔者将RocketMQ的网络模块单独抽取成一个框架，可直接用于项目开发中，代码已上传github</strong></p>
<p><a target="_blank" rel="noopener" href="https://github.com/dingwpmz/netty-learning">Netty项目实战代码仓库</a><br><img src="https://img-blog.csdnimg.cn/20210401000506855.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center" alt="在这里插入图片描述"><br>推荐阅读：</p>
<p><a target="_blank" rel="noopener" href="https://mp.weixin.qq.com/mp/homepage?__biz=MzIzNzgyMjYxOQ==&hid=14&sn=e4672a421e72968b29ad4d796a8d62b1">让天下没有难学的Netty4专栏</a></p>
<hr>
<p>见字如面,我是威哥,一个从普通二本院校毕业,从未曾接触分布式、微服务、高并发到通过<strong>技术分享</strong>实现职场蜕变，成长为RocketMQ社区优秀布道师、大厂资深架构师，出版《RocketMQ技术内幕》一书，在CSDN中记录了我的成长历程，欢迎大家关注，私信，一起交流进步。</p>
<p>分享笔者一个硬核的RocketMQ电子书：<br><img src="https://img-blog.csdnimg.cn/2021032212002741.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center" alt="在这里插入图片描述"></p>
<p>获取方式：扫描如下二维码，关注【中间件兴趣圈】，回复RMQPDF即可获取。</p>
<p><img src="https://img-blog.csdnimg.cn/20190314214003962.jpg?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center" alt="在这里插入图片描述"></p>
</div>

			<script src="https://my.openwrite.cn/js/readmore.js" type="text/javascript"></script>
			<script>
			var isMobile = navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i);
			if (!isMobile) {
			    var btw = new BTWPlugin();
			    btw.init({
			        "id": "vip-container",
			        "blogId": "18019-1573088808868-542",
			        "name": "中间件兴趣圈",
			        "qrcode": "https://img-blog.csdnimg.cn/20190314214003962.jpg",
			        "keyword": "more"
			    });
			}
			</script>
		
      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/posts/78b6e9b7.html" rel="next" title="读写锁在高性能消息中间件RocketMQ中的妙用">
                <i class="fa fa-chevron-left"></i> 读写锁在高性能消息中间件RocketMQ中的妙用
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/posts/c0bbe727.html" rel="prev" title="阿里二面：NIO为什么不适合文件上传场景、如何优雅解决">
                阿里二面：NIO为什么不适合文件上传场景、如何优雅解决 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name"></p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">139</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">18</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#1%E3%80%81%E5%86%99%E4%BA%8B%E4%BB%B6%E6%A6%82%E8%BF%B0"><span class="nav-number">1.</span> <span class="nav-text">1、写事件概述</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2%E3%80%81%E5%86%99%E4%BA%8B%E4%BB%B6%E5%A4%84%E7%90%86%E6%B5%81%E7%A8%8B%E5%88%86%E6%9E%90"><span class="nav-number">2.</span> <span class="nav-text">2、写事件处理流程分析</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#2-1-NIO%E5%86%99%E4%BA%8B%E4%BB%B6%E7%9A%84%E4%BC%98%E9%9B%85%E5%B0%81%E8%A3%85"><span class="nav-number">2.0.1.</span> <span class="nav-text">2.1 NIO写事件的优雅封装</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-2-%E9%80%9A%E9%81%93%E5%86%99%E7%BC%93%E5%86%B2%E5%8C%BA%E8%AF%A6%E8%A7%A3"><span class="nav-number">2.0.2.</span> <span class="nav-text">2.2 通道写缓冲区详解</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#2-2-1-%E7%B1%BB%E5%9B%BE"><span class="nav-number">2.0.2.1.</span> <span class="nav-text">2.2.1 类图</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#2-2-2-size%E6%96%B9%E6%B3%95%E8%AF%A6%E8%A7%A3"><span class="nav-number">2.0.2.2.</span> <span class="nav-text">2.2.2  size方法详解</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#2-2-3-addMessage%E6%96%B9%E6%B3%95%E8%AF%A6%E8%A7%A3"><span class="nav-number">2.0.2.3.</span> <span class="nav-text">2.2.3  addMessage方法详解</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#2-2-4-addMessage%E6%96%B9%E6%B3%95%E8%AF%A6%E8%A7%A3"><span class="nav-number">2.0.2.4.</span> <span class="nav-text">2.2.4  addMessage方法详解</span></a></li></ol></li></ol></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">中间件兴趣圈</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Muse</a> v5.1.4</div>




        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      <i class="fa fa-user"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      
    </span>
  

  
    <span class="site-pv">
      <i class="fa fa-eye"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("NNEhOL0iOcflg8f1U3HUqiCq-gzGzoHsz", "7kSmkbbb3DktmHALlShDsBUF");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  

  
  

  

  

  

</body>
</html>
